<template>
  <div>
    <div class="operation-group">
      <acceptListSelect
        btnText="选择合同物资"
        dialogTitle="选择合同物资"
        :searchInputArr="jsList.planSearchInputArr"
        :tableHeadOptions="jsList.acceptTableHeadOptions"
        :settlement-form="settlementForm"
        @numrow="numrow"
      />

      <!-- <el-button
        plain
        type="single-number"
        :style="{ marginLeft: '10px' }"
        @click="dialogVisible = true"
      >
        批量操作
      </el-button> -->

      <!-- <el-dialog
        title="批量操作"
        :visible.sync="dialogVisible"
        width="400px"
        :before-close="handleClose"
      >
        <div class="el-dialog__body-bodys">
          <el-form :model="form" ref="form" class="ccui-form">
            <el-form-item label="生产厂家/品牌：" prop="brand">
              <el-input
                v-model="form.brand"
                placeholder="请输入生产厂家/品牌"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button
            size="mini"
            type="default-mini"
            @click="dialogVisible = false"
            >取消</el-button
          >
          <el-button size="mini" type="primary-font-mini" @click="btnModify()"
            >确定</el-button
          >
        </div>
      </el-dialog> -->
      <!-- <el-dropdown
        plain
        type="single-number"
        placement="bottom"
        trigger="click"
        @command="batchOperate"
        style="margin-left: 10px"
      >
        <el-button class="search-btn" size="mini">
          其他费用项
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="btn-interest">贴息</el-dropdown-item>
          <el-dropdown-item command="btn-priceRise">价格追涨</el-dropdown-item>
          <el-dropdown-item command="btn-priceFall">价格追跌</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown> -->
      <!-- <el-button plain type="single-number" @click="hebingFun">合并 </el-button> -->
      <!-- <el-button class="ml" plain type="single-number" @click="handleCopy"
        ></el-button
      > -->

      <el-button class="deleteLine" @click="handleDelete">删除行</el-button>
      <!-- :getTableList="listPursckinfoPage" -->
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <ux-grid
        ref="plxTable"
        keep-source
        width="100%"
        widthResize
        show-overflow="title"
        show-summary
        :summary-method="getSummaries"
        :row-class-name="tableRowClassName"
        @select="listSelectTable"
        @select-all="listSelectTable"
        @selection-change="handleSelectionChange"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
      >
        <ux-table-column
          v-if="substr == true"
          type="checkbox"
          min-width="55"
          align="center"
          show-overflow="none"
          fixed="left"
          disabled
        ></ux-table-column>
        <ux-table-column
          v-else
          type="checkbox"
          width="55"
          align="center"
          fixed="left"
          show-overflow="none"
        />

        <ux-table-column
          title="序号"
          min-width="50"
          type="index"
          align="center"
          fixed="left"
          :resizable="true"
        />

        <ux-table-column
          show-overflow-tooltip
          field="materialCode"
          title="设备物资编码"
          min-width="150"
          :resizable="true"
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="materialName"
          title="设备物资名称"
          min-width="300"
          :resizable="true"
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="materialState"
          title="设备物资说明"
          min-width="130"
          :resizable="true"
        >
          <!-- <template slot-scope="{ row }">
            <el-input v-model="row.materialState" />
          </template> -->
        </ux-table-column>

        <!-- <ux-table-column show-overflow-tooltip prop="measureUnit" label="单位">
        </ux-table-column> -->

        <ux-table-column
          show-overflow-tooltip
          field="measureUnit"
          title="计量单位"
          min-width="90"
          :resizable="true"
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="unTransportCount"
          title="剩余可结算数量"
          min-width="140"
          :resizable="true"
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="settlementCount"
          title="结算数量"
          min-width="140"
          :resizable="true"
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <el-input
              v-model="row.settlementCount"
              @keyup.native="row.settlementCount = oninputCount(row)"
              @blur="check_number(row, $event, 'settlementCount')"
            />
          </template>
          <template v-slot="scope">
            <span class="my-input-sc">{{ scope.row.settlementCount }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="taxRatePercent"
          title="税率"
          min-width="90"
          :resizable="true"
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="unitPriceWithTax"
          title="含税单价"
          min-width="140"
          :edit-render="{ autofocus: '.el-input__inner' }"
          :resizable="true"
        >
          <!-- isFloatContractPrice  1固定不可修改，0浮动可修改 -->
          <template v-slot:edit="{ row }">
            <el-input
              v-if="
                settlementForm.smpPcConc &&
                settlementForm.smpPcConc.isFloatContractPrice == 0
              "
              v-model="row.unitPriceWithTax"
              @keyup.native="row.unitPriceWithTax = oninputPrice(row)"
              @blur="check_price(row, $event)"
            />
            <span v-else> {{ row.unitPriceWithTax }}</span>
          </template>
          <template v-slot="scope">
            <span
              :class="{
                'my-input-sc':
                  settlementForm.smpPcConc &&
                  settlementForm.smpPcConc.isFloatContractPrice == 0,
              }"
              >{{ scope.row.unitPriceWithTax }}</span
            >
          </template>
        </ux-table-column>
        <ux-table-column
          show-overflow-tooltip
          field="moneyWithTax"
          title="含税金额"
          min-width="140"
          :resizable="true"
        >
          <template v-slot="{ row }">
            <!-- <el-input
              v-if="row.isOtherCost == 0"
              v-model="row.moneyWithTax"
              readonly
            /> -->
            <!-- v-else-if="substr == false" -->
            <span>{{ row.moneyWithTax }}</span>
            <!-- <el-input v-else v-model="row.moneyWithTax" /> -->
          </template>
        </ux-table-column>
      </ux-grid>
    </div>

    <chooseMaterials
      ref="materialsFormVisible"
      @handleSelect="handleSelect"
      :chooseMaterialsBtn="chooseMaterialsBtn"
    />
  </div>
</template>

<script>
import chooseMaterials from "@/basa/components/public/chooseMaterials";
import jsList from "../js";
import acceptListSelect from "./acceptListSelect";
// import { getAcceptanceCert } from "../api/transportation-approval";
import BigNumber from "bignumber.js";
import { formatNumber } from "@/basa/utils";
export default {
  name: "finaceInfo",
  components: { chooseMaterials, acceptListSelect },
  props: {
    settlementList: {
      type: Array,
    },
    settlementForm: {
      type: Object,
    },
  },
  data() {
    return {
      dialogVisible: false,
      jsList,
      listTableData: [],
      materialVisible: false,
      chooseMaterialsBtn: 0, // 点击选择物资按钮时为true
      checkedLine: [], // 被选中数据
      listId: 0,
      acceptForm: [],
      form: {
        brand: "",
      },
      settlementListInfo: [],
      othersettlementList: [],
      substr: false,
      xxs: [],
      isFloatContractPrice: null, // 是否浮动价
      delIndex: 0,
    };
  },
  watch: {
    settlementForm: {
      handler(newVal, oldVal) {
        if (newVal.smpPcConc) {
          this.isFloatContractPrice = newVal.smpPcConc.isFloatContractPrice;
        }
      },
      deep: true,
    },
    acceptForm: {
      handler(newVal, oldVal) {
        this.$emit("numrows", newVal);
        newVal.forEach((item, index) => {
          item.sn = Number(index) + 1;
        });
        this.$nextTick(() => {
          this.$refs.plxTable.reloadData(newVal);
        });
      },
    },
  },
  created() {},
  mounted() {},
  activited() {},
  update() {},
  methods: {
    // 关闭批量操作弹框
    handleClose(done) {
      done();
    },
    //批量修改项确定按钮
    btnModify() {
      this.listTableData.forEach((item) => {
        this.$set(item, "brand", this.form.brand);
      });
      this.dialogVisible = false;
    },
    // 汇总
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          // sums[index] = "合计";
          sums.push("合计");
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              if (column.title == "结算数量") {
                return new BigNumber(+prev).plus(+curr).toString();
              } else if (column.title == "含税金额") {
                return new BigNumber(+prev).plus(+curr).toString();
              } else {
                return (prev = " ");
              }
            } else {
              return (prev = " ");
            }
          }, 0);
          if (column.title == "结算数量") {
            sums[index] = Number(sums[index]).toFixed(3);
          }
          if (column.title == "含税金额") {
            sums[index] = Number(sums[index]).toFixed(2);
          }
        } else {
          sums[index] = "";
        }

        // 基本信息的结算数量和结算金额根据结算单明细的结算数量和含税金额同步
        this.settlementForm.currSetCount = sums[8];
        this.settlementForm.currSetMoney = sums[10];
      });
      return [sums];
    },
    // 金额四舍五入 8位小数
    calculateFilter(data) {
      if (data || data == 0) {
        if ((data + "").indexOf(".") != -1) {
          let newData = (data + "").substring(0, (data + "").indexOf(".") + 9);
          return newData;
        } else {
          return data;
        }
      } else {
        return "";
      }
    },
    // 金额四舍五入
    numberFilter(data) {
      if (data || data == 0) {
        if ((data + "").indexOf(".") != -1) {
          let newData = (data + "").substring(0, (data + "").indexOf(".") + 4);
          return newData;
        } else {
          return data;
        }
      } else {
        return "";
      }
    },
    oninputCount(row) {
      //      debugger
      //正则替换
      //后来调试发现这个函数只能用于字符串，当是数字的时候就会报此错误
      var str = row.settlementCount.toString();
      str = str.replace(/[^\d.]/g, ""); // 保留数字   /[^\d.]/g, ""
      str = str.replace(/^\./g, ""); // 必须保证第一个为数字而不是.
      str = str.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
      str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      // 限制几位小数
      const arr = str.split(".");
      if (arr[arr.length - 1].length > 3 && arr.length == 2) {
        str = str.substr(0, str.length - 1);
      } else if (arr.length == 1 && str.length > 12) {
        this.$message.warning("整数最多可以输入12位");
        str = str.substr(0, str.length - 1);
      } else if (arr.length == 2 && arr[0].length > 12) {
        this.$message.warning("整数最多可以输入12位");
        str = arr[0].substr(0, arr[0].length - 1);
      }
      return str;
    },
    oninputPrice(row) {
      //      debugger
      //正则替换
      //后来调试发现这个函数只能用于字符串，当是数字的时候就会报此错误
      var str = row.unitPriceWithTax.toString();
      str = str.replace(/[^\d.]/g, ""); // 保留数字   /[^\d.]/g, ""
      str = str.replace(/^\./g, ""); // 必须保证第一个为数字而不是.
      str = str.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
      str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      // 限制几位小数
      const arr = str.split(".");
      if (arr[arr.length - 1].length > 2 && arr.length == 2) {
        str = str.substr(0, str.length - 1);
      } else if (arr.length == 1 && str.length > 12) {
        this.$message.warning("整数最多可以输入12位");
        str = str.substr(0, str.length - 1);
      } else if (arr.length == 2 && arr[0].length > 12) {
        this.$message.warning("整数最多可以输入12位");
        str = arr[0].substr(0, arr[0].length - 1);
      }
      return str;
    },
    // 计算含税金额 start
    check_number(row, event) {
      if (row.settlementCount != "" && row.unitPriceWithTax != "") {
        let reg = /^\d*\.?\d*$/;
        if (reg.test(row.settlementCount)) {
          const arr = row.settlementCount.split(".");
          if (arr.length == 1 && row.settlementCount.length > 12) {
            this.$message.warning("整数最多可以输入12位");
            row.settlementCount = row.settlementCount.substr(0, 12);
          }
        }
        row.settlementCount = row.settlementCount
          ? formatNumber(row.settlementCount, 3)
          : "";

        if (row.unitPriceWithTax) {
          let moneyWithTax = new BigNumber(+row.settlementCount)
            .multipliedBy(+row.unitPriceWithTax)
            .toFixed(2);
          this.$set(row, "moneyWithTax", moneyWithTax);
        }

        let unitPriceWithoutTax = new BigNumber(+row.unitPriceWithTax)
          .dividedBy(1 + +row.taxRate)
          .toFixed(2);
        this.$set(row, "unitPriceWithoutTax", unitPriceWithoutTax);
        let moneyWithoutTax = new BigNumber(+row.moneyWithTax)
          .dividedBy(1 + +row.taxRate)
          .toFixed(2);
        this.$set(row, "moneyWithoutTax", moneyWithoutTax);
      }
    },
    // 计算含税金额 start
    check_price(row, event) {
      if (row.unitPriceWithTax != "") {
        let reg = /^\d*\.?\d*$/;
        if (reg.test(row.unitPriceWithTax)) {
          const arr = row.unitPriceWithTax.split(".");
          if (arr.length == 1 && row.unitPriceWithTax.length > 12) {
            this.$message.warning("整数最多可以输入12位");
            row.unitPriceWithTax = row.unitPriceWithTax.substr(0, 12);
          }
        }
        row.unitPriceWithTax = row.unitPriceWithTax
          ? formatNumber(row.unitPriceWithTax, 2)
          : "";

        if (row.settlementCount) {
          let moneyWithTax = new BigNumber(+row.settlementCount)
            .multipliedBy(+row.unitPriceWithTax)
            .toFixed(2);
          this.$set(row, "moneyWithTax", moneyWithTax);
        }

        let unitPriceWithoutTax = new BigNumber(+row.unitPriceWithTax)
          .dividedBy(1 + +row.taxRate)
          .toFixed(2);
        this.$set(row, "unitPriceWithoutTax", unitPriceWithoutTax);
        let moneyWithoutTax = new BigNumber(+row.moneyWithTax)
          .dividedBy(1 + +row.taxRate)
          .toFixed(2);
        this.$set(row, "moneyWithoutTax", moneyWithoutTax);
      }
    },
    // 计算含税金额 end
    // 采购方案选择确认
    programmeConfirm(data) {
      console.log("采购方案选中行==>>", data);
    },
    tableRowClassName(data) {
      if (data.row.isMerge == 1 && data.row.isMainInventory == 0) {
        return "hidden-row";
      }
      return "";
    },
    // 选择材料
    handleChooseMaterials() {
      // 打开新增物资清单页面
      this.$refs.materialsFormVisible.dialogFormVisible = true;
      this.chooseMaterialsBtn++;
    },
    // 采购清单选中数据
    listSelectTable(val) {
      this.listTableData = val;
    },
    handleSelect(row) {},
    // 选择合同物资
    numrow(row) {
      let newArr = JSON.parse(JSON.stringify(row));
      newArr.forEach((_item, _index) => {
        _item.contractId = _item.concId;
        _item.unTransportCount = _item.residualSettlementNumber.toFixed(3);
        _item.settlementCount = _item.unTransportCount;
        _item.moneyWithTax =
          _item.settlementCount && _item.currentUnitPriceIncludeTax
            ? new BigNumber(+_item.settlementCount)
                .multipliedBy(+_item.currentUnitPriceIncludeTax)
                .toString()
            : "";
        _item.moneyWithTax = _item.moneyWithTax
          ? Number(_item.moneyWithTax).toFixed(2)
          : "";

        _item.materialFirstId = _item.firstId;
        _item.materialId = _item.id;
        _item.categoryCode = _item.thirdCategoriesOfCode;
        _item.categoryName = _item.thirdCategoriesOfName;
        _item.materialCode = _item.materialsCode;
        _item.materialName = _item.materialsName;
        _item.materialState = _item.matDescribe;
        _item.measureUnit = _item.currentMeasuringUnit;
        _item.measureUnitCode = _item.currentMeasuringUnitCode;
        _item.unitPriceWithTax = _item.currentUnitPriceIncludeTax;
        _item.delIndex = this.delIndex++;
        _item.unitPriceWithoutTax = new BigNumber(+_item.unitPriceWithTax)
          .dividedBy(1 + +_item.taxRate)
          .toFixed(2);
        _item.moneyWithoutTax = new BigNumber(+_item.moneyWithTax)
          .dividedBy(1 + +_item.taxRate)
          .toFixed(2);
      });
      for (let i = 0; i < newArr.length; i++) {
        this.acceptForm.push(newArr[i]);
      }
    },
    //删除行
    handleDelete() {
      if (this.checkedLine.length < 1) {
        this.$message.warning("请选择一项");
        return;
      }
      var mergeUuidSet = new Set();
      for (var i = 0; i < this.checkedLine.length; i++) {
        mergeUuidSet.add(this.checkedLine[i].delIndex);
      }
      for (i = this.acceptForm.length - 1; i >= 0; i--) {
        if (mergeUuidSet.has(this.acceptForm[i].delIndex)) {
          this.acceptForm.splice(i, 1);
        }
      }
    },
    // 获取选中
    handleSelectionChange(val) {
      this.checkedLine = val;
    },
    generateUUID() {
      var d = new Date().getTime();
      var uuid = "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
          var r = (d + Math.random() * 16) % 16 | 0;
          d = Math.floor(d / 16);
          return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
        }
      );
      return uuid;
    },
  },
  filter: {},
  computed: {},
};
</script>

<style lang="scss" scoped>
/deep/ .ccui-multifunctional-table-wrapper {
  .el-table td,
  .el-table th.is-leaf {
    border-right: 1px solid #edf2fc;
  }
}

.ml {
  margin-left: 10px;
}

.operation-group {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
}

/deep/
  .ccui-multifunctional-table-wrapper
  .el-table
  tbody
  tr
  td:first-child
  .cell {
  border-right: 1px solid #f1f1f1;
}

.deleteLine {
  padding: 0 20px;
  height: 30px;
  background: #f7f9ff;
  border: 1px solid #0089ef;
  border-radius: 4px;
  position: relative;
  color: #0089ef;
  margin-left: 10px;
}

/deep/ .hidden-row {
  display: none;
}

/deep/ .el-dropdown {
  margin-right: 10px;

  button {
    background: #f7f9ff;
    border: 1px solid #0089ef;
    color: #0089ef;
  }
}

/deep/ .el-form-item__content .el-input {
  width: 167px;
}

/deep/ .el-table__fixed-header-wrapper {
  th {
    pointer-events: auto;
  }
}

/deep/ .el-table__fixed,
/deep/ .el-table__fixed-right {
  pointer-events: none;

  td {
    pointer-events: auto;
  }
}
/deep/.el-table--border {
  th:last-of-type.gutter {
    display: table-cell !important;
    width: 0px !important;
  }
}

.my-input-sc {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  -webkit-appearance: none;
  background-color: #ffffff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606266;
  font-size: inherit;
  outline: none;
  padding: 0 8px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}
</style>
